<template>
  <div class="app">
    <div class="login-container">
      <div class="login-logo">
        <p class="login-title">欢迎使用</p>
        <h1 class="login-title">智能调度系统</h1>
      </div>

      <div class="login-form">
        <el-form ref="loginRef" :model="loginForm" :rules="loginRules">
          <div class="form-item">
            <el-form-item prop="username">
              <el-input v-model="loginForm.username" :placeholder="proxy.$t('login.username')" auto-complete="off" size="large"
                type="text">
                <template #prefix><svg-icon class="el-input__icon input-icon" icon-class="user" /></template>
              </el-input>
            </el-form-item>
          </div>

          <div class="form-item">
            <el-form-item prop="password">
              <el-input v-model="loginForm.password" :placeholder="proxy.$t('login.password')" auto-complete="off" size="large"
                type="password" @keyup.enter="handleLogin">
                <template #prefix><svg-icon class="el-input__icon input-icon" icon-class="password" /></template>
              </el-input>
            </el-form-item>
            <el-form-item v-if="captchaEnabled" prop="code">
              <el-input v-model="loginForm.code" :placeholder="proxy.$t('login.code')" auto-complete="off" size="large"
                style="width: 63%" @keyup.enter="handleLogin">
                <template #prefix><svg-icon class="el-input__icon input-icon" icon-class="validCode" /></template>
              </el-input>
              <div class="login-code">
                <img :src="codeUrl" class="login-code-img" @click="getCode" />
              </div>
            </el-form-item>
            <el-checkbox v-model="loginForm.rememberMe" style="margin: 0 0 25px 0">{{ proxy.$t('login.rememberPassword')
            }}</el-checkbox>
          </div>

          <div class="form-item">
            <el-button :loading="loading" class="login-btn" native-type="submit" type="primary"
              @click.prevent="handleLogin">
              <span v-if="!loading">{{ proxy.$t('login.login') }}</span>
              <span v-else>{{ proxy.$t('login.logging') }}</span>
            </el-button>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { getCodeImg, getTenantList } from '@/api/login';
import { useUserStore } from '@/store/modules/user';
import { LoginData, TenantVO } from '@/api/types';
import { to } from 'await-to-js';
import { authBinding } from '@/api/system/social/auth';
import { HttpStatus } from '@/enums/RespEnum';
import { useI18n } from 'vue-i18n';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const title = import.meta.env.VITE_APP_TITLE;
const userStore = useUserStore();
const router = useRouter();
const { t } = useI18n();

const loginForm = ref<LoginData>({
  tenantId: '000000',
  username: 'admin',
  password: 'admin123',
  rememberMe: false,
  code: '',
} as LoginData);

const codeUrl = ref('');
const loading = ref(false);
// 验证码开关
const captchaEnabled = ref(true);
// 租户开关
const tenantEnabled = ref(true);

// 注册开关
const register = ref(false);
const redirect = ref('/processWorkOrder');
const loginRef = ref<ElFormInstance>();
// 租户列表
const tenantList = ref<TenantVO[]>([]);

watch(
  () => router.currentRoute.value,
  (newRoute: any) => {
    // redirect.value = newRoute.query && newRoute.query.redirect ? decodeURIComponent(newRoute.query.redirect) : '/menu';
    redirect.value = '/processWorkOrder';
  },
  { immediate: true }
);


const loginRules: ElFormRules = {
  username: [{ required: true, trigger: 'blur', message: t('login.rule.username.required') }],
  password: [{ required: true, trigger: 'blur', message: t('login.rule.password.required') }],
  code: [{ required: true, trigger: 'change', message: t('login.rule.code.required') }]
}

const handleLogin = () => {
  loginRef.value?.validate(async (valid: boolean, fields: any) => {
    if (valid) {
      loading.value = true;
      // 勾选了需要记住密码设置在 localStorage 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        localStorage.setItem('tenantId', String(loginForm.value.tenantId));
        localStorage.setItem('username', String(loginForm.value.username));
        localStorage.setItem('password', String(loginForm.value.password));
        localStorage.setItem('rememberMe', String(loginForm.value.rememberMe));
      } else {
        // 否则移除
        localStorage.removeItem('tenantId');
        localStorage.removeItem('username');
        localStorage.removeItem('password');
        localStorage.removeItem('rememberMe');
      }
      // 调用action的登录方法
      const [err] = await to(userStore.login(loginForm.value));
      if (!err) {
        const redirectUrl = redirect.value || '/processWorkOrder';
        console.log(redirectUrl, "redirectUrl")
        await router.push(redirectUrl);
        loading.value = false;
      } else {
        loading.value = false;
        // 重新获取验证码
        if (captchaEnabled.value) {
          await getCode();
        }
      }
    } else {
      console.log('error submit!', fields);
    }
  });
};
/**
 * 获取验证码
 */
const getCode = async () => {
  const res = await getCodeImg();
  const { data } = res;
  captchaEnabled.value = data.captchaEnabled === undefined ? true : data.captchaEnabled;
  if (captchaEnabled.value) {
    codeUrl.value = 'data:image/gif;base64,' + data.img;
    loginForm.value.uuid = data.uuid;
  }
};
/**
 * 获取租户列表
 */
const initTenantList = async () => {
  const { data } = await getTenantList(false);
  tenantEnabled.value = data.tenantEnabled === undefined ? true : data.tenantEnabled;
  if (tenantEnabled.value) {
    tenantList.value = data.voList;
    if (tenantList.value != null && tenantList.value.length !== 0) {
      loginForm.value.tenantId = tenantList.value[0].tenantId;
    }
  }
};
const getLoginData = () => {
  const tenantId = localStorage.getItem('tenantId');
  const username = localStorage.getItem('username');
  const password = localStorage.getItem('password');
  const rememberMe = localStorage.getItem('rememberMe');
  loginForm.value = {
    tenantId: tenantId === null ? String(loginForm.value.tenantId) : tenantId,
    username: username === null ? String(loginForm.value.username) : username,
    password: password === null ? String(loginForm.value.password) : String(password),
    rememberMe: rememberMe === null ? false : Boolean(rememberMe)
  } as LoginData;
  console.log(loginForm.value, "  loginForm.value")
};

onMounted(() => {
  getCode();
  initTenantList();
  getLoginData();
});
</script>

<style lang="scss" scoped>
@use "sass:map";

// 定义断点变量
$breakpoints: (
  'xs': 0,
  'sm': 576px,
  'md': 768px,
  'lg': 992px,
  'xl': 1200px,
  'xxl': 1400px
);

// 媒体查询混入
@mixin respond-to($breakpoint) {
  @if map.has-key($breakpoints, $breakpoint) {
    @media (min-width: map.get($breakpoints, $breakpoint)) {
      @content;
    }
  }

  @else {
    @warn "Unknown breakpoint `#{$breakpoint}`. Using default values.";
  }
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.app {
  background: url('@/assets/login/loginbei.png');
  background-repeat: no-repeat;
  background-position: center;
  background-size: cover;
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  padding: 20px;
  position: relative;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.3);
    z-index: 1;
  }

  @include respond-to('sm') {
    padding: 30px;
  }

  @include respond-to('md') {
    padding: 40px;
  }
}

.login-container {
  position: relative;
  z-index: 2;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 30px 20px;
  width: 100%;
  max-width: 400px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);

  @include respond-to('sm') {
    padding: 40px 30px;
    max-width: 450px;
  }

  @include respond-to('md') {
    padding: 50px 40px;
    max-width: 600px;
  }
}

.login-logo {
  text-align: center;
  margin-bottom: 30px;

  @include respond-to('md') {
    margin-bottom: 40px;
  }

  img {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);

    @include respond-to('md') {
      width: 100px;
      height: 100px;
    }
  }
}

.login-title:nth-child(1) {
  font-size: 17px;
  font-weight: 600;
  margin-top: 15px;
  color: #999;
  text-align: center;
  letter-spacing: 0.5px;

  @include respond-to('md') {
    font-size: 17px;
    margin-top: 20px;
  }
}

.login-title {
  font-size: 24px;
  font-weight: 600;
  margin-top: 15px;
  color: #2c3e50;
  text-align: center;
  letter-spacing: 0.5px;

  @include respond-to('md') {
    font-size: 28px;
    margin-top: 20px;
  }
}

.login-form {
  margin-bottom: 30px;

  @include respond-to('md') {
    margin-bottom: 40px;
  }
}

.form-item {
  margin-bottom: 20px;

  .el-input {
    .el-input__wrapper {
      border-radius: 12px;
      border: 2px solid #e1e8ed;
      transition: all 0.3s ease;
      background: rgba(255, 255, 255, 0.9);

      &:hover {
        border-color: #409eff;
      }

      &.is-focus {
        border-color: #409eff;
        box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
      }
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 0px;
  }

  .login-code {
    width: 33%;
    height: 40px;
    float: right;

    img {
      cursor: pointer;
      vertical-align: middle;
      border-radius: 8px;
    }
  }

  .login-code-img {
    height: 40px;
    padding-left: 12px;
  }

  @include respond-to('md') {
    margin-bottom: 25px;
  }
}

.login-footer {
  text-align: center;
  margin-top: 30px;
  color: #666;
  font-size: 14px;

  a {
    color: #409eff;
    text-decoration: none;
    font-weight: 500;
    transition: color 0.3s ease;

    &:hover {
      color: #337ecc;
    }
  }

  @include respond-to('md') {
    margin-top: 40px;
    font-size: 16px;
  }
}

.login-btn {
  width: 100%;
  border-radius: 12px;
  height: 48px;
  font-size: 16px;
  font-weight: 600;
  background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
  border: none;
  transition: all 0.3s ease;
  box-shadow: 0 4px 16px rgba(64, 158, 255, 0.3);

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(64, 158, 255, 0.4);
  }

  &:active {
    transform: translateY(0);
  }
}

.forgot-password {
  text-align: center;
  margin-top: 15px;

  a {
    color: #666;
    text-decoration: none;
    font-size: 14px;
    transition: color 0.3s ease;

    &:hover {
      color: #409eff;
    }
  }
}

.other-login {
  margin-top: 30px;

  @include respond-to('md') {
    margin-top: 40px;
  }
}

.divider {
  display: flex;
  align-items: center;
  margin: 20px 0;
  color: #999;
  font-size: 14px;

  .divider-line {
    flex: 1;
    height: 1px;
    background: #e1e8ed;
  }

  .divider-text {
    padding: 0 15px;
  }
}

.other-login-methods {
  display: flex;
  justify-content: center;
  gap: 30px;

  @include respond-to('sm') {
    gap: 40px;
  }
}

.other-login-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  transition: transform 0.3s ease;

  &:hover {
    transform: translateY(-2px);
  }
}

.other-login-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
  margin-bottom: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);

  &.wechat {
    background: linear-gradient(135deg, #07C160 0%, #06AD56 100%);
  }

  &.qq {
    background: linear-gradient(135deg, #12B7F5 0%, #0F9BD4 100%);
  }
}

.other-login-text {
  font-size: 12px;
  color: #666;
  font-weight: 500;
}

/* 移动端适配调整 */
:deep(.el-form-item__content) {
  margin-left: 0 !important;
}

:deep(.el-input__inner) {
  height: 44px !important;
  line-height: 44px !important;
}

:deep(.el-input__prefix),
:deep(.el-input__suffix) {
  display: flex;
  align-items: center;
}

:deep(.el-form-item) {
  margin-bottom: 20px;

  @include respond-to('md') {
    margin-bottom: 25px;
  }
}

.custom-input-with-icon :deep(.el-input__prefix) {
  display: flex;
  align-items: center;
}

.custom-input-with-icon :deep(.el-input__prefix-inner) {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  color: #1989fa;
  margin-right: 8px;
}

.custom-input-with-icon :deep(.el-input__prefix-inner .el-icon) {
  font-size: 18px;
}
</style>
